
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Category;
import com.cmc.dao.CategoryDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class CategoryDaoHibernate extends BaseDaoHibernate implements CategoryDao {

    /**
     * @see com.cmc.dao.CategoryDao#getCategorys(com.cmc.model.Category)
     */
    public List getCategorys(final Category category) {
        //return getHibernateTemplate().find("from Category");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (category == null) {
            return getHibernateTemplate().find("from Category");
        } else {
            // filter on properties set in the category
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(category).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Category.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.CategoryDao#getCategory(Long id)
     */
    public Category getCategory(final Long id) {
        Category category = (Category) getHibernateTemplate().get(Category.class, id);
        if (category == null) {
            log.warn("uh oh, category with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Category.class, id);
        }

        return category;
    }

    /**
     * @see com.cmc.dao.CategoryDao#saveCategory(Category category)
     */    
    public void saveCategory(final Category category) {
        getHibernateTemplate().saveOrUpdate(category);
    }

    /**
     * @see com.cmc.dao.CategoryDao#removeCategory(Long id)
     */
    public void removeCategory(final Long id) {
        getHibernateTemplate().delete(getCategory(id));
    }
}
